<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\DB;

class User extends Authenticatable
{
    /**
     * 登录操作并生成日志
     */
    public function do_login($mobile,$pwd,$ip,$pwd2)
    {
        $status = 4;
        $user = DB::select("select `id` from `users` where `status`=1 and `mobile`='$mobile' and `pwd`='$pwd'");
        if($user){
            $status = 1;
            $user = json_decode(json_encode($user),true);
            $user = $user[0];
        }
        $sql = "insert into `log` (account,login_ip,login_pwd,`status`) ".
            "values ('$mobile','$ip','$pwd2',$status)";
        DB::insert($sql);
        if ($user) {
            return $user['id'];
        }
        return 0;
    }

    /**
     * 修改会员资料
     */
    public function user_update($data)
    {
        $res = $this->where(['id'=>$data['id']])->update($data);
        return $res;
    }

    /**
     * 生成验证码
     */
    public function create_code($mobile, $code)
    {
        $sql = "select * from `users` where `mobile`='$mobile'";
        $res = DB::select($sql);
        if (!$res) {
            DB::delete("delete from `identifying` where `account`='$mobile'");
            $sql = "insert into `identifying` (account, code, `status`) values ('$mobile', '$code', 0)";
            $res = DB::insert($sql);
            if ($res){
                return 200;
            }
            return 2;
        }
        return 1;
    }

    /**
     * 验证 CODE
     */
    public function verify_code($mobile, $code)
    {
        $sql = "select * from `identifying` where `account`='$mobile' and `code`='$code'";
        $res = DB::select($sql);
        return $res ? $res[0] : false;
    }

    /**
     * 用户注册
     */
    public function register($data)
    {
        $id = DB::table('users')->insertGetId($data);
        if ($id){
            $id_e = DB::table('user_ex')->insertGetId(array('user_id'=>$id));
            if ($id_e){
                return $id;
            }
        }
        return false;
    }

    /**
     * 获取用户信息
     */
    public function get_usre($where)
    {
        $user = $this->where($where)->first();
        return $user;
    }

}
